<!-- 收藏管理 - 弹框 -->
<template>
    <el-dialog 
    :title="typeTitle+'收藏网站'"
    v-model="dialogVisible"
    width="45%"
    :close-on-click-modal="false" 
    :close-on-press-escape="true"
    @closed="resetForm(formRef)">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
            <el-form-item label="网站类别" prop="type">
                <el-select v-model="form.type" placeholder="请选择网站类别" :disabled="billState" @change="typeSelectChange">
                    <el-option v-for="item in websiteList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="网站名称" prop="name">
                <el-input v-model="form.name" :readonly="billState" placeholder="请输入网站名称"></el-input>
            </el-form-item>
            <el-form-item label="网站图标" prop="cover">
                <el-input v-model="form.cover" :readonly="billState" placeholder="请输入网站图标"></el-input>
            </el-form-item>
            <el-form-item label="网站地址" prop="url">
                <el-input v-model="form.url" :readonly="billState" placeholder="请输入网站地址"></el-input>
            </el-form-item>
            <el-form-item label="网站简介" prop="desc">
                <el-input type="textarea" v-model="form.desc" :readonly="billState" placeholder="网站简介"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="">
                <el-radio-group :disabled="billState" v-model="form.state">
                    <el-radio v-for="item in stateList" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span>
                <el-button type="primary" class="" v-if="dialogState == 'add'" :loading="submitLoading" @click="submitClick">确定</el-button>
                <el-button type="primary" class="" v-if="dialogState == 'update'" :loading="updateLoading" @click="updateClick">确定</el-button>
                <el-button class="" @click="resetForm(formRef)">关闭</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { favoriteApi } from '@/api/article/favorite/favorite-api';
import { ElMessage } from 'element-plus';
import { reactive } from 'vue';
import { WEBSITE_REGEXP } from '@/utils/verify-util';


// ========================= 弹框控制 =========================
let dialogVisible = ref(false);
let dialogState = ref('add');
function onShowDialog(type, row) {
    if(row) {
        for(let key in form) {
            form[key] = row[key];
        };
        form.id = row.id;
    };
    dialogState.value = type;
    dialogVisible.value = true;
};

// 组件向外暴露属性或方法
defineExpose({
    onShowDialog
});

// ========================= 计算属性 =========================
const typeTitle = computed(() => {
    if(dialogState.value == 'add') return '新增';
    if(dialogState.value == 'update') return '修改';
    if(dialogState.value == 'view') return '查看';
});

const billState = computed(() => {
    if(dialogState.value != 'view') return false;
    return true;
});

// ========================= 定义发射给父组件的方法 =========================
const emits = defineEmits(['updateParentList']);

// ========================= 表单 =========================
const form = reactive({
    id:'',                  // 主键
    type:'',                // 网站类别
    typeName:'',            // 网站类别名称
    name:'',                // 网站名称
    cover:'',               // 网站图标
    url:'',                 // 网站地址
    desc:'',                // 网站简介
    state: true,            // 状态
    createdAt:'',           // 创建时间
    updatedAt:'',           // 更新时间
});
// 网址校验
const valiWebsite = (rule, value, callback) => {
    if(WEBSITE_REGEXP.test(value)) {
        callback();
    }else {
        callback(new Error('请输入正确的网站地址'));
    };
};
const rules = reactive({
    type: [
        { required: true, message: '请输入网站类别', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入网站名称', trigger: 'blur' }
    ],
    url: [
        { required: true, message: '请输入网站地址', trigger: 'blur' },
        { validator: valiWebsite, trigger: 'blur' }
    ],
});

let stateList = reactive([
    {label: '正常', value: true},
    {label: '停用', value: false},
]);
// 网站类别
let websiteList = reactive([
    { label:'编程帮手', value:1 },
    { label:'博客', value:2 },
    { label:'前端', value:3 },
    { label:'后端', value:4 },
    { label:'协作办公', value:5 },
]);
// 类别名称
function typeSelectChange(value) {
    websiteList.forEach(item => {
        if(item.value === value) {
            form.typeName = item.label;
            return;
        };
    });
};

// 表单操作
const formRef = ref();
let submitLoading = ref(false);
// 提交
function submitClick() {
    formRef.value.validate(async (valid) => {
        try {
            if(valid) {
                submitLoading.value = true;
                let date = new Date();
                form.createdAt = date;
                form.updatedAt = date;
                delete form.id;
                const res = await favoriteApi.create(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success('新增成功');
                submitLoading.value = false;
                dialogVisible.value = false;
                emits('updateParentList');
            }
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            submitLoading.value = false;
        };
    })
};


// 更新
let updateLoading = ref(false);
function updateClick() {
    formRef.value.validate(async (valid) => {
        try {
            if(valid) {
                updateLoading.value = true;
                let date = new Date();
                form.updatedAt = date;
                const res = await favoriteApi.update(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success('修改成功');
                updateLoading.value = false;
                dialogVisible.value = false;
                emits('updateParentList');
            };
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        }finally {
            updateLoading.value = false;
        };
    });
};
// ========================= 重置表单 =========================
function resetForm(refFormName) {
    refFormName.resetFields(); // 重置表单
    for(let key in form) {
        form[key] = ''
    };
    dialogVisible.value = false;
    form.state = true;
};
</script>

<style lang="scss" scoped>

</style>